# -*- coding: utf-8 -*-
"""
    lantz.foreign
    ~~~~~~~~~~~~~

    Implements classes and methods to interface to foreign functions.

    :copyright: (c) 2012 by Lantz Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from lantz import Action, Feat, DictFeat
from lantz.serial import SerialDriver
from lantz.errors import InstrumentError
from time import sleep
from lantz import Q_
from pylab import *
import numpy as np

class ArduinoSCPI(SerialDriver):
    """Template for drivers connecting via serial port.
    """

    ENCODING = 'ascii'

    RECV_TERMINATION = '\n'
    SEND_TERMINATION = '\n'
    
    TIMEOUT=20
    
    BAUDRATE=115200

    @Feat()
    def idn(self):
        """Help for a a_read_only_property
        """
        return self.query('*IDN?')
    
    
   
    @Feat(units='V', limits=(5,))
    def Voltage(self):
        """Get the voltage on analog0
        """
        return float(self.query(':MEAS:VOLT?'))
        
    @Feat(units='V', limits=(5,))
    def Voltage2(self):
        """Get the voltage on analog0
        """
        return float(self.query(':MEAS:VOLT2?'))
                   
  
    @Action()
    def TestInputADC(self):
        """Loop of 10 acquisitions
        """
        print('Ready for 10 acquisitions')        
        R=[]        
        for i in range(10):
            V=self.Voltage
            
            print(V)
            sleep(0.1)
            
            R=R,V
        x = randn(10000)
        hist(x, 100)
        return  R  

        

if __name__ == '__main__':
    import argparse
    import lantz.log

    

    parser = argparse.ArgumentParser(description='Test SR 830')
    parser.add_argument('-i', '--interactive', action='store_true',
                        default=False, help='Show interactive GUI')
    parser.add_argument('-p', '--port', type=str, default='/dev/cu.usbserial',
                        help='Serial port to connect to')

    args = parser.parse_args()
    lantz.log.log_to_screen(lantz.log.DEBUG)
    #lantz.log.log_to_socket(lantz.log.DEBUG)
    with ArduinoSCPI(args.port) as inst:
        if args.interactive:
            from lantz.ui.qtwidgets import start_test_app
            start_test_app(inst)
            
        else:
            #test code
            print('Non interactive mode')
            #print(inst.TestInputADC())
            print(inst.idn())
            #print(inst.TestInputNoise())
            #print(inst.TestInputDCOffset())